package sc.tool.sqlgen.branchinfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

/**
 * <p>文件解析器</p>
 * @author Shi
 * @version $Id: FileParser.java, v 0.1 2010-8-6 下午02:00:53 Shi Exp $
 */
public class FileUtil {
    /** 分隔符 */
    private static final String SPLIT_TAG = ",";
    /** 忽略标记 */
    private static final String IGNORE_TAG = "#";

    /**
     * 获取文件内容
     * @param filePath
     * @param splitTag 分隔标识
     * @return
     */
    public static List<String[]> loadItems(String filePath, String splitTag) {
        List<String[]> itemList = new ArrayList<String[]>();
//        ClassPathResource resource = new ClassPathResource(".");

        BufferedReader reader = null;
        try {
//            String path = resource.getFile().getAbsolutePath();
            File file = new File(filePath);

            reader = new BufferedReader(new FileReader(file));

            String tempString = null;
            // 一次读入一行，直到读入空为文件结束
            while (StringUtils.isNotBlank(tempString = reader.readLine())) {
                if (tempString.indexOf(IGNORE_TAG) == 0) {
                    continue;
                }
                itemList.add(tempString.split(StringUtils.isBlank(splitTag) ? SPLIT_TAG : splitTag));
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        return itemList;
    }

    /**
     * 写文件
     * @param items
     * @param filePath
     */
    public static void writeFile(List<String> items, String filePath) {
        try {
            File file = new File(filePath);

            FileOutputStream os = new FileOutputStream(file, true);
            for (String item : items) {
                os.write((item + "\n").getBytes());
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 采用默认分隔标识
     * @param filePath
     * @return
     */
    public static List<String[]> loadItems(String filePath) {
        return loadItems(filePath, null);
    }
}
